import React, { useEffect } from 'react';
import * as echarts from 'echarts';
import './styles.css'; // 引入样式

interface EChartsComponentProps {
    chartType: 'line' | 'pie';
    data: any;
    chartId: string; // 新增 chartId 属性
}

const EChartsComponent: React.FC<EChartsComponentProps> = ({ chartType, data, chartId }) => {
    useEffect(() => {
        const chartContainer = document.getElementById(chartId)!;
        const myChart = echarts.init(chartContainer);

        let option;

        if (chartType === "line") {
    option = {
        tooltip: {},
        legend: {
            data: data.seriesData.map((item: any) => item.name),
            bottom: '0%',
            orient: 'horizontal',
            icon: 'circle', // 设置图例为实心圆点
        },
        xAxis: {
            type: "category",
            data: data.xAxisData,
        },
        yAxis: { type: "value" },
        series: data.seriesData.map((item: any) => ({
            name: item.name,
            type: "line",
            data: item.data,
        })),
    };
}
 else if (chartType === "pie") {
            option = {
                tooltip: {
                    trigger: 'item',
                    formatter: (params: any) => {
                        return `制作数量<br/>${params.name}: ${params.value}`;
                    },
                },
                series: [
                    {
                        name: "访问来源",
                        type: "pie",
                        radius: "50%",
                        data: data.seriesData,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: "rgba(0, 0, 0, 0.5)",
                            },
                        },
                        label: {
                            show: true,
                        },
                        labelLine: {
                            show: false,
                        },
                    },
                ],
            };
        }

        myChart.setOption(option);

        window.addEventListener("resize", myChart.resize);

        return () => {
            window.removeEventListener("resize", myChart.resize);
            myChart.dispose();
        };
    }, [chartType, data, chartId]);

    const chartClassName = chartType === 'pie' ? 'pie-chart' : 'line-chart';

    return <div id={chartId} className={chartClassName} />;
};

export default EChartsComponent;
